package controllers.listeners.ontology;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import objects.Concept;

import views.MainPanel;
import views.ViewOntology;

/* Highlights panels on the MainPanel with the same concept */
/* actionPerformed when you click on the table */
public class OntologyTableMouseListener implements MouseListener {
	
	private MainPanel mp;
	private ViewOntology view;
	private Concept concept;
	
	public OntologyTableMouseListener() {
		mp = null;
		view = null;
		concept = null;
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		concept = view.getSelectedConcept();
		JPanel semrepPanel = mp.getSentencePanel();
		
		/* Exit if no concept selected */
		if (concept == null) {
			JOptionPane.showMessageDialog(null, "Please select a concept.", "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		/* Exit if no loaded sem rep */
		if (semrepPanel.getComponents().length <= 0) {
			return;
		}
		
		/* Highlight them panels */
		highlight(semrepPanel);
	}
	
	private boolean highlight(Component currentComponent) {
		if (currentComponent.getClass() == JPanel.class) {
			MouseListener mouseListener = null;
			try {
				mouseListener = currentComponent.getMouseListeners()[0];
			}
			catch (Exception ex) {}
			
			for (Component component : ((JPanel) currentComponent).getComponents()) {
				try {
					if (highlight(component)) {
						mouseListener.mouseEntered(null);
					}
					else {
						mouseListener.mouseExited(null);
					}
				}
				catch (Exception ex) {}
			}
		}
		else if (currentComponent.getClass() == JLabel.class) {
			JLabel currentLabel = (JLabel) currentComponent;
			String[] labelText = currentLabel.getText().split("-");
			
			/* Check if they have the same concept */ 
			if (labelText[0].toLowerCase().equals(concept.getName().toLowerCase())) {
				if (labelText.length < 2) {
					return true;
				}
				else if (labelText[1].toLowerCase().equals(concept.getSense().toLowerCase())) {
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public void mouseEntered(MouseEvent e) {}
	
	@Override
	public void mouseExited(MouseEvent e) {}
	
	@Override
	public void mousePressed(MouseEvent e) {}
	
	@Override
	public void mouseReleased(MouseEvent e) {}
	
	public void setMainPanel(MainPanel mp) {
		this.mp = mp;
	}
	
	public void setView(ViewOntology view) {
		this.view = view;
	}
	
}
